//
//  main.c
//  demo3
//
//  Created by Song on 2018/3/6.
//  Copyright © 2018年 Song. All rights reserved.
//
//  双向链表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//typedef struct gggg {
//    int data;
//    struct gggg *prior;
//    struct gggg *next;
//}node,*head;
//// head h = malloc(sizeof(node)); // 创建头结点

typedef struct node pnode;
struct node {
    
    pnode *prior;
    int data;
    pnode *next;
};

// 输出链表
void PrintList(pnode *head) {
    pnode *p;
    p = head->next;
    if (p == NULL) {
        printf("the list is empty\n");
    }
    for (p = head->next; p != NULL; p = p->next) {
        printf("%d",p->data);
    }
    printf("\n");
    pnode *temp;
//    temp = p->prior;
//    printf("最后一个：%d \n 倒数第二个：%d\n",p->data,temp->data);
}

// 初始化链表，尾插法
pnode *InitList(pnode *head, int n) {
    pnode *phead, *pnew, *ptail;
    
    phead = (pnode *)malloc(sizeof(pnode));
    if (phead == NULL) {
        printf("init - head - null");
        return 0;
    }
    phead->prior = NULL;
    phead->next = NULL;
    ptail = phead; // 初始时，尾指针指向头结点
    
    int i;
    for (i = 0; i < n; ++i) {
        pnew = (pnode *)malloc(sizeof(pnode));
        if (pnew == NULL) {
            printf("init - pnew - null");
            return 0;
        }
        printf("输入节点的值：");
        scanf("%d",&pnew->data);
        
        pnew->next = NULL;
        ptail->next = pnew;
        pnew->prior = ptail;
        ptail = pnew;
        
        printf(" == %d\n",pnew->prior->data);
    }
    
    return phead;
}




int main(int argc, const char * argv[]) {
    
    int n,element,flag;
    pnode *head, *last;
    
    printf("输入链表的长度：");
    scanf("%d",&n);
    head = InitList(head, n);//初始化链表并赋值,返回尾节点last

    PrintList(head);
    
    return 0;
}
